#include "stdafx.h"
#include "Utility.h"
#include "InputManager.h"
#include "CommandConsts.h"
#include "CommandDispatcher.h"
#include "MemTrack.h"

namespace bs
{
	InputManager::InputManager(HWND hwnd) : InputSniffer(hwnd)
	{
		CommandDispatcher::Instance().RegisterProcessor(WIN_MSG_CMD, this);
	}

	InputManager::~InputManager()
	{
		CommandDispatcher::Instance().UnregisterProcessor(this);
	}

	BEGIN_COMMAND_MAP(InputManager)
		COMMAND_MAP_ENTRY(WIN_MSG_CMD, WIN_MSG_LBTN_STATUS, OnKeyStatus)
		COMMAND_MAP_ENTRY(WIN_MSG_CMD, WIN_MSG_CURSOR_SCRPOS, OnCursorScrPos)
		COMMAND_MAP_ENTRY(WIN_MSG_CMD, WIN_MSG_CURSOR_WINPOS, OnCursorWinPos)
	END_COMMAND_MAP()

	void InputManager::Run(int id, size_t time, size_t frames, size_t elapse, void *userData)
	{
		this->GetCursorScreenPos();

		Command* cmd = NULL;
		cmd = new Command(WIN_MSG_CMD, WIN_MSG_LBTN_STATUS);
		cmd->SetValue(this->lBtnDown);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_RBTN_STATUS);
		cmd->SetValue(this->rBtnDown);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_MBTN_STATUS);
		cmd->SetValue(this->mBtnDown);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_LBTN_CLK);
		cmd->SetValue(this->lBtnClk);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_RBTN_CLK);
		cmd->SetValue(this->rBtnClk);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_MBTN_CLK);
		cmd->SetValue(this->mBtnClk);
		CommandDispatcher::Instance().SendCommand(cmd);

		cmd = new Command(WIN_MSG_CMD, WIN_MSG_CURSOR_WINPOS);
		cmd->SetParam(&this->cursorWinPos);
		CommandDispatcher::Instance().SendCommand(cmd);
	}

	void InputManager::OnKeyStatus(const Command& cmd)
	{
		int* key = (int*)cmd.GetSrc();
		bool* status = (bool*)cmd.GetDst();

		if(!key || !status || *key<0 || *key>=MAX_KEY_SIZE)
			return;

		*status = this->keyStatus[*key];
	}

	void InputManager::OnCursorScrPos(const Command& cmd)
	{
		Point* pt = (Point*)cmd.GetParam();

		if(!pt)
			return;

		*pt = this->cursorScrPos;
	}

	void InputManager::OnCursorWinPos(const Command& cmd)
	{

		Point* pt = (Point*)cmd.GetParam();

		if(!pt)
			return;

		*pt = this->cursorWinPos;
	}

}

